from aiogram import Bot, Dispatcher, F
from aiogram.filters import Text
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import any_state
from aiogram.types import Message
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from sqlalchemy.ext.asyncio import AsyncSession

from app.bot.keyboards.reply import user_keyboard
from app.bot.states.states import Unique
from app.bot.utils.logger import log
from app.bot.utils.scheduler import jobs
from app.database.functions.stats import update_stats, update_user_stats
from app.database.functions.unique import add_unique


async def add_task(message: Message, state: FSMContext) -> None:
    """
    Добавление задачи на уникализацию фото/видео
    """

    await message.answer("Раздел в разработке")
    # await message.answer('Отправьте мне фото/видео и я отправлю вам его уникализированную версию')
    # await Unique.waiting_file.set()


async def select_file(
    message: Message,
    bot: Bot,
    session: AsyncSession,
    scheduler: AsyncIOScheduler,
    state: FSMContext,
) -> None:
    if message.video is not None:
        file_name = message.video.file_name
        file = await bot.get_file(message.video.file_id)
        file_path = file.file_path
        await bot.download_file(file_path, f"bot/images/{file_name}")
        await message.answer(
            "Ваша задача принята в работу", reply_markup=user_keyboard()
        )
    elif message.photo is not None:
        file_name = message.photo[-1].file_unique_id
        file = await bot.get_file(message.photo[-1].file_id)
        file_path = file.file_path
        await bot.download_file(file_path, f"bot/images/{file_name}.jpg")
        # 		await message.bot.send_document(message.chat.id, (file_name, open(file_name, 'rb')))
        await message.answer(
            "Ваша задача принята в работу", reply_markup=user_keyboard()
        )
    await state.clear()
    await add_unique(session, message.from_user.id, file_name)
    scheduler.add_job(
        jobs.check_uniques,
        "interval",
        name="Unique photo/video",
        minutes=1,
        args=(bot, message.from_user.id),
    )
    log.info(
        f"Добавлена задача по уникализации креатива для пользователя {message.from_user.id}"
    )
    await update_stats(session, uniques=1)
    await update_user_stats(session, message.from_user.id, uniques=1)


def register_unique_handlers(dp: Dispatcher):
    dp.message.register(
        add_task, Text(text="📹 Уникализация фото/видео", ignore_case=True), any_state
    )
    dp.message.register(
        select_file,
        Unique.waiting_file,
        F.content_type.in_(["photo", "video"]),
    )
